package org.sq;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;

public class QuestFragment extends Fragment {

	private static final String TAG = "sq";
	WebView webView;
	EditText answerField;
	Button sendBtn;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.quest, container, false);
		final LevelManager levelManager = ((SQApp) getActivity().getApplicationContext()).levelManager();

		answerField = (EditText) view.findViewById(R.id.answer_field);
		webView = (WebView) view.findViewById(R.id.web_view);
		sendBtn = (Button) view.findViewById(R.id.send_btn);

		WebSettings webSettings = webView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setSupportZoom(false);
		webSettings.setAllowFileAccess(true);
		webSettings.setLoadsImagesAutomatically(true);
		webSettings.setSavePassword(false);
		webSettings.setSaveFormData(false);
		webSettings.setJavaScriptEnabled(true);
		webView.setWebViewClient(new SQWebViewClient());

		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			Log.d(TAG, "No SDCARD");
		} else {
			webView.loadUrl("file://" + getActivity().getFilesDir().getPath()
					+ LevelManager.QUESTS_PATH + "/"
					+ levelManager.getCurrentLevel() + "/quest.html");
		}

		sendBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sendAction(v);

			}
		});
		return view;
	}

	private class SQWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (url.endsWith(".mp3")) {
				Log.d("SQWebViewClient", "Try open file: " + url);

				File oldFile = new File(URI.create(url));

				File externalDir = getActivity().getExternalFilesDir(null);
				File newFile = new File(externalDir, oldFile.getName());

				if (!newFile.exists()) {
					try {
						copy(oldFile, newFile);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(newFile), "audio/*");
				view.getContext().startActivity(intent);
				return true;
			} else if (url.endsWith(".mp4") || url.endsWith(".3gp")) {

				File oldFile = new File(URI.create(url));

				File externalDir = getActivity().getExternalFilesDir(null);
				File newFile = new File(externalDir, oldFile.getName());

				if (!newFile.exists()) {
					try {
						copy(oldFile, newFile);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(newFile), "video/*");
				view.getContext().startActivity(intent);
				return true;
			} else {
				return super.shouldOverrideUrlLoading(view, url);
			}
		}
	}

	public void copy(File src, File dst) throws IOException {
		InputStream in = new FileInputStream(src);
		OutputStream out = new FileOutputStream(dst);
		Log.d("CopyFile", "Src size: " + src.length());
		// Transfer bytes from in to out
		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		Log.d("CopyFile", "Dst size: " + dst.length());
		in.close();
		out.close();
	}

	public void onStart() {
		super.onStart();
		final LevelManager levelManager = ((SQApp) getActivity()
				.getApplicationContext()).levelManager();

		Log.d("QuestFragment", "onStart");
		webView.loadUrl("file://" + getActivity().getFilesDir().getPath()
				+ LevelManager.QUESTS_PATH + "/"
				+ levelManager.getCurrentLevel() + "/quest.html");
	}

	public void sendAction(View v) {
		final LevelManager levelManager = ((SQApp) getActivity()
				.getApplicationContext()).levelManager();

		if (levelManager.checkAnswer(answerField.getText().toString().trim())) {
			if (levelManager.readNextLevel()) {
				answerField.setText("");
				webView.loadUrl("file://"
						+ getActivity().getFilesDir().getPath()
						+ LevelManager.QUESTS_PATH + "/"
						+ levelManager.getCurrentLevel() + "/quest.html");
			} else {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						getActivity());
				builder.setMessage(getString(R.string.game_end))
						.setTitle(getString(R.string.info, null))
						.setPositiveButton(getString(R.string.ok, null), null)
						.show();
			}
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setMessage(getString(R.string.answer_incorrect))
					.setTitle(getString(R.string.info, null))
					.setPositiveButton(getString(R.string.ok, null), null)
					.show();
		}
	}

}
